package com.jinghong.registerlogin.service.impi;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jinghong.registerlogin.ai.V4OkHttpClientTest;
import com.jinghong.registerlogin.mapper.*;
import com.jinghong.registerlogin.model.dto.UpdatePaperDTO;
import com.jinghong.registerlogin.model.pojo.*;
import com.jinghong.registerlogin.model.vo.PaperVO;
import com.jinghong.registerlogin.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:PapperServiceimpi
 * Package:com.jinghong.registerlogin.service.impi
 * Description:
 *
 * @Author: 寻月君子
 * @CreatTime:2024/5/22 15:22
 * Version:1.0
 */
@Service
public class PaperServiceimpi implements PaperService {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private EvaluationMapper evaluationMapper;
    @Autowired

    private EvaluationQuestionMapper evaluationQuestionMapper;

    @Override
    public void insert(Paper paper) {
        paperMapper.insert(paper);
    }

    @Override
    public PageBean list(Integer page, Integer pageSize, String subject,String topic, Integer userId, Integer status, LocalDateTime begin, LocalDateTime end) {
        //1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        //2. 执行查询
        List<Paper> patientList = paperMapper.list(subject,topic,userId,status,begin,end);
        Page<Paper> p = (Page<Paper>) patientList;

        //3. 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

    @Override
    public Paper get(Integer id) {
        return paperMapper.getById(id);
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        Paper paper = new Paper();
        paper.setId(id);
        paper.setStatus(status);
        paperMapper.update(paper);
    }

    @Override
    public void delete(Integer id) {
        //删除试卷
        paperMapper.deleteById(id);
        //删除试卷与问题关联
        paperQuestionMapper.deleteByPaperId(id);
        //删除考核评价与问题关联
        List<Integer> ids = evaluationMapper.getByPaperId(id);
        evaluationQuestionMapper.deleteByEvaluationId(ids);
        //删除评价
        evaluationMapper.deleteByPaperId(id);

    }

    @Override
    public void update(Paper paper) {
        paperMapper.update(paper);
    }

    @Override
    public void deleteQuestion(UpdatePaperDTO updatePaperDTO) {
        Paper paper = updatePaperDTO.getPaper();
        List<Integer> questionIds = updatePaperDTO.getQuestionIds();
        questionIds.forEach(questionId->{
            Question question = questionMapper.getById(questionId);
            Short type = question.getType();
            if (type == 1){
                paper.setSingleNum(paper.getSingleNum()-1);
            }else if (type == 2){
                paper.setMultipleNum(paper.getMultipleNum()-1);
            }else if (type == 3){
                paper.setJudgeNum(paper.getJudgeNum()-1);
            }else {
                paper.setWordNum(paper.getWordNum()-1);
            }
        });
        paperQuestionMapper.bulkDelete(paper.getId(),questionIds);
        paperMapper.update(paper);
    }

    @Override
    public PaperVO getIntirePaper(Integer id) {

        //通过试卷id回显试卷
        Paper paper = paperMapper.getById(id);
        //通过试卷id得到问题ids
        List<PaperQuestion> paperQuestions = paperQuestionMapper.getByPaperId(id);
        List<Integer> ids = new ArrayList<>();
        for (PaperQuestion paperQuestion : paperQuestions) {
            ids.add(paperQuestion.getQuestionId());
        }
        List<Question> questions = questionMapper.bulkGet(ids);
        return new PaperVO(paper,questions);
    }

    @Override
    public void generateAndInsertPaper(Paper paper) {
        List<Question> questions = GenerateAllQuestions(paper);
        //在数据库中插入试卷
        paperMapper.insert(paper);
        //在数据库中插入试卷里的问题
        questionMapper.bulkInsert(questions);
        //记录总分
        Integer sumScore = 0;
        //将试卷id和试卷里的每道题目的id关联起来放入集合中
        List<PaperQuestion> paperQuestions = new ArrayList<>();
        for (Question question : questions) {
            //将每道题目分数都加起来
            sumScore += question.getScore();
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paper.getId());
            paperQuestion.setQuestionId(question.getId());
            paperQuestions.add(paperQuestion);
        }
        //为试卷总分赋值
        paper.setTotalScore(sumScore);
        paperMapper.update(paper);
        //在数据库中批量插入试卷与题目关联
        paperQuestionMapper.bulkInsert(paperQuestions);
    }

    private List<Question> GenerateAllQuestions(Paper paper) {
        List<Question> questions = new ArrayList<>();

        for (int i = 1; i <= 4; i++) {
            questions = generateQuestion(questions, paper, i);
        }

        return questions;
    }


    //生成单种类型问题
    private List<Question> generateQuestion(List<Question> questions, Paper paper, int questionType) {
        String typeName;
        int questionNum;
        if (questionType == 1 && paper.getSingleNum() != 0) {
            typeName = "单选题";
            questionNum = paper.getSingleNum();
        } else if (questionType == 2 && paper.getMultipleNum() != 0) {
            typeName = "多选题";
            questionNum = paper.getMultipleNum();
        } else if (questionType == 3 && paper.getJudgeNum() != 0) {
            typeName = "判断题";
            questionNum = paper.getJudgeNum();
        } else if (questionType == 4 && paper.getWordNum() != 0) {
            typeName = "简答题";
            questionNum = paper.getWordNum();
        } else {
            return questions;
        }
        String content = "是一个出题机器,能根据<<<题目要求>>>出题,并转化为JSON格式数据,不需要要在代码块里展示,在这个 JSON 对象中，question中type代表题目类型,其中1为单选题,2为多选题,3为判断题,4为简答题.如果type是1和2,optionNum为选项数量,a,b,c,d,e,为选项内容,answer为答案选项大写.如果type为3和4,optionNum,a,b,c,d,e属性都为空,answer为该题答案,detail为该题解析.所有题目的userId为" + paper.getUserId() + ".\n" +
                "###\n" +
                "题目要求例子\n" +
                "请出关于豌豆杂交类的题目,属于高中生物学科,知识面程度只涉及高中阶段,题目数量为5道\n" +
                "回答例子\n" +
                " { “questions”: [{“content”: “在豌豆杂交实验中，如果一个纯合子与另一个纯合子杂交，那么它们的后代将会是？”, “type”: “1”, “optionNum”: “4”, “a”: “纯合子”, “b”: “杂合子”, “c”: “显性”, “d”: “隐性”, “e”: “”, “score”: “5”, “answer”: “A”, “detail”: “在豌豆杂交实验中，纯合子与纯合子杂交后代将会是纯合子。”,“userId”:“5” },{ “content”: “在豌豆杂交实验中，哪些是显性性状？”, “type”: “2”, “optionNum”: “5”, “a”: “花色”, “b”: “种子形状”, “c”: “种皮颜色”, “d”: “叶型”, “e”: “茎的高度”, “score”: “3”, “answer”: “ABCD”, “detail”: “在豌豆杂交实验中，显性性状包括花色、种子形状、种皮颜色和叶型。”,“userId”:“5”}]}" +
                "###\n" +
                "<<<\n" +
                "请出关于题目,属于" + paper.getSubject() + "学科,知识面程度只涉及" + paper.getLevel() + "难度为" + paper.getDifficulty() + ",出" + questionNum + "道" + typeName + "\n" +
                ">>>";
        String answer = V4OkHttpClientTest.testInvoke(content);
        answer = answer.substring(answer.indexOf('{'), answer.lastIndexOf('}') + 1);
        JSONObject jsonObject = JSONObject.parseObject(answer);
        String questionsJson = JSONArray.toJSONString(jsonObject.get("questions"));
        List<Question> question1 = JSON.parseArray(questionsJson, Question.class);
        System.out.println(question1);
        questions.addAll(question1);
        return questions;
    }
}
